import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class globalCors implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    // 允许所有域名访问（或指定允许的域名）
    res.header('Access-Control-Allow-Origin', '*');

    // 允许跨域请求的方法
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

    // 允许跨域请求携带的头信息
    res.header('Access-Control-Allow-Headers', 'Content-Type, Accept, X-Requested-With, Authorization');

    // 允许跨域请求携带 Cookies
    res.header('Access-Control-Allow-Credentials', 'true');

    // 处理预检请求
    if (req.method === 'OPTIONS') {
      res.sendStatus(200);
    } else {
      next();
    }
  }
}